<template>
  <div>
    <FormItemRest>
      <MapModal v-model:value="address" @success="handleSuccess">
        <a-input
          readonly
          :disabled="disabled"
          :placeholder="placeholder"
          v-model:value="address"
          :size="size"
          :bordered="bordered"
          @blur="emit('blur')"
        >
          <template #prefix v-if="prefix">
            <Icon :icon="prefix" />
          </template>
          <template #suffix v-if="suffix">
            <Icon :icon="suffix" />
          </template>
        </a-input>
      </MapModal>
    </FormItemRest>
  </div>
</template>
<script lang="ts" setup>
  import { Form } from 'ant-design-vue';
  import { MapModal } from '/@/components/Map/index';
  import { watch, ref, inject } from 'vue';
  import { Icon } from '/@/components/Icon';

  import { camelCaseString } from '/@/utils/event/design';
  // 用于包裹弹窗的form组件 因为一个FormItem 只能收集一个表单组件  所以弹窗的form 必须排除
  const FormItemRest = Form.ItemRest;

  const props = defineProps({
    value: String,
    prefix: String,
    suffix: String,
    placeholder: String,
    readonly: Boolean,
    disabled: Boolean,
    size: String,
    bordered: {
      type: Boolean,
      default: true,
    },
    address: String,
    latiAndLong: String,
    index: Number,
    mainKey: String,
  });

  const address = ref<string>();

  const emit = defineEmits(['update:value', 'change', 'blur']);

  const formModel = inject<any>('formModel', null); // 注入表单数据
  const isCustomForm = inject<boolean>('isCustomForm', false);

  watch(
    () => props.value,
    () => {
      address.value = props.value;
      if (!props.value) {
        //预览页面 重置
        address.value = '';
      }
    },
    {
      immediate: true,
    },
  );

  function handleSuccess(v) {
    console.log('MAP handleSuccess ', v);
    changeFieldData(v);
    emit('update:value', v.address);
    emit('change', v.address);
  }
  function changeFieldData(v) {
    if (!formModel) return;
    if (props.address) {
      const addressField: any = isCustomForm ? props.address : camelCaseString(props.address);
      if (props.mainKey && props.index !== undefined && props.index !== null) {
        formModel[props.mainKey][props.index][addressField] = v.address;
      } else {
        formModel[addressField] = v.address;
      }
    }
    if (props.latiAndLong) {
      const latiAndLong: any = isCustomForm
        ? props.latiAndLong
        : camelCaseString(props.latiAndLong);
      if (props.mainKey && props.index != undefined && props.index !== null) {
        formModel[props.mainKey][props.index][latiAndLong] = v.lnglat.join(',');
      } else {
        formModel[latiAndLong] = v.lnglat.join(',');
      }
    }
  }
</script>
